#include <string.h>
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


struct result{
  char str[1024];
  struct result *next;
};



jstring
Java_com_explorer_ExplorerActivity_stringFromJNI( JNIEnv* env,
						  jobject thiz )
{
  FILE *read_fp;
  char buffer[BUFSIZ+1];
  int chars_read;

  struct result *head=NULL;
  struct result *prev,*current;


  read_fp=popen("ps ","r");
  if(read_fp!=NULL){
    int tag=1;
    while(tag){
      current=(struct result *)malloc(sizeof (struct result));
      chars_read=fread(current->str,sizeof(char),BUFSIZ,read_fp);
      if( head == NULL){
	head=current;
      }else{
	prev->next=current;
      }
      current->next=NULL;
      prev=current;
      if(chars_read<=0){
	tag=0;
      }
    }
    pclose(read_fp);
      
    current=head;
    int length=0;
    while(1){
      if(current!=NULL){
	length+=strlen(current->str);
      }else{
	break;
      }
      current=current->next;
    }

    char *buff=(char *)malloc((length+1)*sizeof(char));
    /* copy result */
    current=head;
    while(1){
      if(current!=NULL){
	strcat(buff,current->str);
      }else{
	break;
      }
      current=current->next;
    }
    return (*env)->NewStringUTF(env, buff);
  }
}

